package cn.yyx.empservice.controller;


import cn.yyx.common.R;
import cn.yyx.empservice.entity.attendance.Attendance;
import cn.yyx.empservice.entity.attendance.Query;
import cn.yyx.empservice.entity.employee.Employee;
import cn.yyx.empservice.service.AttendanceService;
import cn.yyx.empservice.service.EmployeeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sun
 * @since 2023-10-25
 */
@RestController
@RequestMapping("/attendance")
public class AttendanceController {
    @Autowired
    private AttendanceService attendanceService;
    @Autowired
    private EmployeeService employeeService;

    /**
     * 查询请假列表
     * @param query
     * @return
     */
    @PostMapping("list")
    public R leaveList(@RequestBody Query query){
        QueryWrapper<Attendance> queryWrapper = new QueryWrapper<>();
        if(!ObjectUtils.isEmpty(query.getName())){
            queryWrapper.like("name",query.getName());
        }
        if(!ObjectUtils.isEmpty(query.getEmpId())){
            queryWrapper.eq("emp_id",query.getEmpId());
        }
        if(!ObjectUtils.isEmpty(query.getBegin()) && !ObjectUtils.isEmpty(query.getEnd())){
            queryWrapper.between("leave_time",query.getBegin(),query.getEnd());
        }
        List<Attendance> attendanceList = attendanceService.list(queryWrapper);
        if (CollectionUtils.isEmpty(attendanceList)){
            return R.error();
        }
        for (Attendance attendance :     attendanceList) {
            Employee employee = employeeService.getById(attendance.getEmpId());
            attendance.setName(employee.getName());
        }
        return R.ok().data("items",attendanceList);
    }

    /**
     * 添加请假
     * @param attendance
     * @return
     */
    @PostMapping("add")
    public R addLeave(@RequestBody Attendance attendance){
        attendance.setLeaveTime(new Date());
        return attendanceService.save(attendance)?R.ok():R.error();
    }

    /**
     * 根据编号查找请假信息
     * @param id
     * @return
     */
    @GetMapping("getById/{id}")
    public R getLeaveById(@PathVariable String id){
        return R.ok().data("item",attendanceService.getById(id));
    }

    /**
     * 根据编号修改请假信息
     * @param attendance
     * @return
     */
    @PostMapping("update")
    public R updateLeave(@RequestBody Attendance attendance){
        return attendanceService.updateById(attendance)?R.ok():R.error();
    }

}

